<template>
  <div class="login-wrap">
    <div class="login-box">
      <div><img src="../../assets/a.jpg" alt="" /></div>
      <div class="login-R">
        <h3>系统登录</h3>
        <el-form
          ref="ruleFormRef"
          :model="ruleForm"
          :rules="rules"
          label-width="200px"
          class="demo-ruleForm"
        >
          <el-form-item label="账户" prop="username">
            <el-input v-model="ruleForm.username" />
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="ruleForm.password" />
          </el-form-item>

          <el-form-item>
            <el-button
              type="primary"
              @click="submitForm(ruleFormRef)"
              style="width: 100%"
              >登录</el-button
            >
          </el-form-item>
        </el-form>
        <p @click="() => $router.push('/sign')">Or注册用户</p>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref } from "vue";
import { login } from "../../api";
import cookie from "js-cookie";
import { ElMessage } from 'element-plus'
const ruleFormRef = ref();

const ruleForm = ref({
  username: "",
  password: "",
});

const rules = ref({
  username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }],
});

const submitForm = async (formEl: any) => {
  if (!formEl) return;
  await formEl.validate((valid: any, fields: any) => {
    if (valid) {
      login({
        username: ruleForm.value.username,
        password: ruleForm.value.password,
      }).then((resp: any) => {
        console.log(resp.data);
        if (resp.data.code === 200) {
          cookie.set("token", resp.data.token);
          ElMessage({
            message: resp.data.msg,
            type: "success",
          });
          window.location.href='/'
        }else{
          ElMessage.error(resp.data.msg)
        }
      });
    } else {
      console.log("登陆失败!", fields);
    }
  });
};
</script>

<style lang="scss" scoped>
.login-wrap {
  width: 100%;
  height: 100%;
  background: #ccc;
  box-sizing: border-box;
}
.login-box {
  width: 80%;
  height: 83%;
  display: flex;
  align-items: center;
  background: #eee;
  margin: 0 auto;
  position: fixed;
  top: 10%;
  left: 10%;
}
</style>